package com.edu.control.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Value("${deploy.thread.corePoolSize:2}")
    private Integer deployThreadCorePoolSize;
    @Value("${deploy.thread.maxPoolSize:2}")
    private Integer deployThreadMaxPoolSize;
    @Value("${deploy.thread.queueCapacity:50}")
    private Integer deployQueueCapacity;
    @Value("${deploy.thread.name.prefix:deploy-}")
    private String deployThreadNamePrefix;
    @Value("${deploy.thread.keep.alive.seconds:60}")
    private Integer deployKeepAliveSeconds;

    @Bean("deployThreadPool")
    public ThreadPoolTaskExecutor getDeployThreadPoolExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数量
        threadPoolTaskExecutor.setCorePoolSize(deployThreadCorePoolSize);
        //最大线程数量
        threadPoolTaskExecutor.setMaxPoolSize(deployThreadMaxPoolSize);
        //队列中最大任务数
        threadPoolTaskExecutor.setQueueCapacity(deployQueueCapacity);
        //线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(deployThreadNamePrefix);
        //当达到最大线程数时如何处理新任务
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后最大存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(deployKeepAliveSeconds);
        //初始化线程池
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
